// pages/library/index.js
Page({
    
    /**
     * 页面的初始数据
     */
    data: {
        keyWord: "", //输入查询关键字
        list: [], //存放查询结果
        history: [], //存放历史记录
        searchList: [],
        inputText: '',
        isFocus: false
    },



    searchBook: function (e) {
        let keyWord = this.data.keyWord
        let db = wx.cloud.database("library")
        let _ = db.command
        // this.setData({
        //     keyWord:keyWord
        // })
        console.log("e.detail is", e.detail)
        console.log("keyWord is", keyWord)
        //输入为空
        if (keyWord == '') {
            wx.showModal({
                title: '提示',
                content: '还没有该本书的资源，可以在界面中提供需求哦～',
              })
            return
        } 
        else if (keyWord != '') {
            try {
                let value = wx.getStorageSync('history')
                if(value){
                  // 最多缓存20条记录
                  this.data.searchList = JSON.parse(value).slice(0,20)
                }
                //去重
                let index = this.data.searchList.indexOf(keyWord)
                if(index > -1){
                  this.data.searchList.splice(index,1)
                }
                this.data.searchList.unshift(keyWord)
                wx.setStorageSync('history', JSON.stringify(this.data.searchList))
              }catch(e){
                console.log(e)
              }
              // 搜索成功后跳转页面，并清空searchList
            this.clearList()
        }
        
        //模糊查询
        db.collection('library').where(_.or([{
                    title: db.RegExp({
                        regexp: keyWord,
                        options: 'i',
                    }),
                },
                {
                    label: db.RegExp({
                        regexp: keyWord,
                        options: 'i',
                    }),
                }
            ])).get()
            .then(res => {
                console.log("查询成功", res)
                if (res.data.length == 0) {
                    wx.showModal({
                        title: '提示',
                        content: '还没有该本书的资源，可以在界面中提供需求哦～',
                      })
                    return
                }

                //动态将查询结果存入list数组
                this.setData({
                    list: res.data
                })

                console.log("list数组为", this.data.list)
                let result = encodeURIComponent(JSON.stringify(this.data.list))
                wx.navigateTo({
                    url: '/pages/search-result/index?result=' + result,
                    success: console.log("跳转成功")
                })
            })
            .catch(res => {
                console.log("查询失败")
            })
    },

    searchKind: function (e) {
        let keyWord = e.currentTarget.dataset.kind
        console.log(keyWord)
        let db = wx.cloud.database("library")
        let _ = db.command


        //模糊查询
        db.collection('library').where(_.or([{
                    title: db.RegExp({
                        regexp: keyWord,
                        options: 'i',
                    }),
                },
                {
                    label: db.RegExp({
                        regexp: keyWord,
                        options: 'i',
                    }),
                }
            ])).get()
            .then(res => {
                console.log("查询成功", res)
                if (res.data.length == 0) {
                    wx.showModal({
                        title: '提示',
                        content: '还没有该本书的资源，可以在界面中提供需求哦～',
                      })
                    return
                }

                //动态将查询结果存入list数组
                this.setData({
                    list: res.data
                })

                console.log("list数组为", this.data.list)
                // encodeURIComponent(JSON.stringify(obj))
                let result = encodeURIComponent(JSON.stringify(this.data.list))
                wx.navigateTo({
                    url: '/pages/search-result/index?result=' + result,
                    success: console.log("跳转成功")
                })
            })
            .catch(res => {
                console.log("查询失败")
            })
    },

    uploadfile: function () {
        // var that = this
        wx.chooseMessageFile({
            count: 1,
            type: 'file',
            success(res) {
                //文件临时路径
                const tempFilePaths = res.tempFiles[0].path
                //后缀名的获取
                const houzhui = tempFilePaths.match(/\.[^.]+?$/)[0];
                //存储在云存储的地址
                const cloudpath = 'File_Collection/' + new Date().getTime()+ houzhui;
                //获取fileID
                wx.cloud.uploadFile({
                    cloudPath: cloudpath,
                    filePath: tempFilePaths,
                    success: res => {
                        //返回文件ID
                        console.log(res.fileID)
                        this.setData({
                            fileid: res.fileID
                        })
                        wx.showModal({
                            title: '提示',
                            content: '文件上传成功',
                          })
                    },
                    fail: err => {
                        console.log(err)
                        wx.showModal({
                            title: '提示',
                            content: '文件上传失败',
                          })
                    },
                })
                wx.showModal({
                    title: '提示',
                    content: '文件上传成功',
                  })
            }
        })
    },



    searchMsg(e){
        const that = this
        if(e.detail.value != ''){
          try {
            let value = wx.getStorageSync('history')
            if(value){
              // 最多缓存20条记录
              that.data.searchList = JSON.parse(value).slice(0,20)
            }
            //去重
            let index = this.data.searchList.indexOf(e.detail.value)
            if(index > -1){
              this.data.searchList.splice(index,1)
            }
            that.data.searchList.unshift(e.detail.value)
            wx.setStorageSync('history', JSON.stringify(that.data.searchList))
          }catch(e){
            console.log(e)
          }
          // 搜索成功后跳转页面，并清空searchList
        this.clearList()
        }
      },

    // 聚焦且无输入值时显示所有历史记录，有输入值时显示包含其的所有历史记录
    showHistory(e){
        //获取缓存数据
        const that = this
        if(!e.detail.value){
          try {
            let value = wx.getStorageSync('history')
            if (value) {
              that.setData({
                // 只展示5个
                searchList:JSON.parse(value).slice(0,5)
              })
            }
          } catch (e) {
          }
        }else {
          this.findHistory('',e.detail.value)
        }
      },

    //点击历史记录进行填充搜索
    reSearch(e){
        this.setData({
          inputText:e.currentTarget.dataset.text,
          // 这个聚焦方法会出现闪动的情况
          isFocus:true,
          keyWord:e.currentTarget.dataset.text
        })
        this.searchBook(this.data.inputText)
      },

    clearList() {
        this.setData({
            searchList: []
        })
    },

    // 查找搜索历史记录
    findHistory(e,param){
        this.setData({
            keyWord: e.detail
        })
    const that = this
    let temp = []
    let p = param ? param : e.detail.value
    if(p){
      try{
        let value = wx.getStorageSync('history')
        if(value){
          JSON.parse(value).forEach((item,index)=>{
            if(item.indexOf(p) > -1){
              temp.unshift(item)
            }
          })
        }
      }catch(e){
        console.log(e)
      }
    }else {
      temp = JSON.parse(wx.getStorageSync('history')).slice(0,5)
    }
    that.setData({
      searchList:temp
    })
  },

    navigatecommit: function(){
        wx.navigateTo({
          url: '/pages/lib-commit/index',
          success: console.log("跳转到commit成功")
        })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})